//
//  GMReadPDFVC.m
//  Teecloud
//
//  Created by 小熊 on 2018/12/6.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "GMReadPDFVC.h"
#import "CGContextDrawPDFPageController.h"
#import "GMCommentBaseModel.h"
#import "GMReadPdfView.h"
#import "GMCommentVC.h"
#import "GMQustionVC.h"
#import "GMKnowlegeVC.h"
#import "GMNoteVC.h"
#import "GMExercisesVC.h"
#import "GMEnclosureVC.h"
#import "GMLookPDFVC.h"
@interface GMReadPDFVC ()
@property (nonatomic, strong) GMCommentBaseModel *model;
@property (nonatomic, assign) NSInteger totalPages;
@property (nonatomic, strong) GMReadPdfView *bottomView;
@property (nonatomic, assign) NSInteger currentPag;
@end

@implementation GMReadPDFVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kWhiteColor;
    [self addRightBarButtonWithFirstImage:[UIImage imageNamed:@"share_white"] action:@selector(shareMyFile)];
    [self addLeftBarButtonWithImage:[UIImage imageNamed:@"left-white-64"] action:@selector(left_BarButtonItemAction)];
    [self getMyFileData];
}
- (void)left_BarButtonItemAction {
    if (kIsEmptyString(self.typeStr)) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}
- (void)getMyFileData{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:self.groupId forKey:@"groupId"];
    [dict setValue:self.resId forKey:@"resId"];
    [dict setValue:self.packId forKey:@"packId"];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetResDetail&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                GMCommentBaseModel *baseModel = [GMCommentBaseModel mj_objectWithKeyValues:[responseObject objectForKey:RESULT_NAME_Data]];
                self.model = baseModel;
                self.title =baseModel.Name;
                [self downLoadPDFwithUrl:baseModel.Url];
                [self updateReadWithPag:1];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"请求出错" toView:self.view];
        }
    }];
}
- (void)downLoadPDFwithUrl:(NSString *)url{
    //如果是rar或者zip直接下载
    NSArray *array = [url componentsSeparatedByString:@"/"];
    NSString *fileName =[array lastObject];
    [MBProgressHUD showErrorOrSuc:@"处理中" toView:self.view];
    [HJNetwork downloadWithURL:url fileDir:TENYUNDOWN fileName:fileName progress:^(NSProgress *progress) {
       
    } callback:^(NSString *path, NSError *error) {
        if (!error) {
            [self creatPDFwithPath:fileName];
        }else{
            [MBProgressHUD showErrorOrSuc:@"文件打开失败" toView:self.view];
        }
    }];
}
- (void)creatPDFwithPath:(NSString *)path{
    /* 根据pdf文件路径初始化pdf阅读视图 */
    //拼接缓存目录
    NSString *downloadDir = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:TENYUNDOWN];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@",downloadDir,path];
    //创建CGPDFDocument对象
    CGPDFDocumentRef pdfDocument =  [self createPDFFromExistFile:filePath]; // 创建pdf文件对象
    pdfPageModel = [[CGContextDrawPDFPageModel alloc] initWithPDFDocument:pdfDocument];
    kWeakObject(self)
    pdfPageModel.pageBlock = ^(NSInteger curentPag) {
        weakself.currentPag =curentPag;
        NSLog(@"%ld",curentPag);
        [weakself updateReadWithPag:curentPag];
    };
    // UIPageViewControllerSpineLocationMin 单页显示
    NSDictionary *options = [NSDictionary dictionaryWithObject:
                             [NSNumber numberWithInteger: UIPageViewControllerSpineLocationMin]
                                                        forKey: UIPageViewControllerOptionSpineLocationKey];
    //初始化UIPageViewController，UIPageViewControllerTransitionStylePageCurl翻页效果，UIPageViewControllerNavigationOrientationHorizontal水平方向翻页
    pageViewCtrl = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStylePageCurl
                                                   navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal
                                                                 options:options];
    //承载pdf每页内容的控制器
    CGContextDrawPDFPageController *initialViewController = [pdfPageModel viewControllerAtIndex:1];
    NSArray *viewControllers = [NSArray arrayWithObject:initialViewController];
    //设置UIPageViewController的数据源
    [pageViewCtrl setDataSource:pdfPageModel];
    //设置正反面都有文字
    pageViewCtrl.doubleSided = YES;
    pageViewCtrl.view.frame = CGRectMake(0, 0, self.view.frame.size.width,self.view.frame.size.height-50);
    //设置pageViewCtrl的子控制器
    [pageViewCtrl setViewControllers:viewControllers
                           direction:UIPageViewControllerNavigationDirectionReverse
                            animated:NO
                          completion:^(BOOL f){}];
    [self addChildViewController:pageViewCtrl];
    [self.view addSubview:pageViewCtrl.view];
    //当我们向我们的视图控制器容器（就是父视图控制器，它调用addChildViewController方法加入子视图控制器，它就成为了视图控制器的容器）中添加（或者删除）子视图控制器后，必须调用该方法，告诉iOS，已经完成添加（或删除）子控制器的操作。
    [pageViewCtrl didMoveToParentViewController:self];
    [self.view addSubview:self.bottomView];
    self.bottomView.model = self.model;
}
/* 根据文件路径创建pdf文件 */
- (CGPDFDocumentRef)createPDFFromExistFile:(NSString *)aFilePath {
    CFStringRef path;
    CFURLRef url;
    CGPDFDocumentRef document;
    
    path = CFStringCreateWithCString(NULL, [aFilePath UTF8String], kCFStringEncodingUTF8);
    url =  CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, NO);
    CFRelease(path);
    
    document = CGPDFDocumentCreateWithURL(url);
    CFRelease(url);
    self.totalPages = CGPDFDocumentGetNumberOfPages(document); // 设置PDF文件总页数
    if (self.totalPages == 0) { // 创建出错处理
        NSLog(@"Create Error");
        return NULL;
    }
    return document;
}

- (GMReadPdfView *)bottomView{
    if (!_bottomView) {
        _bottomView = [GMReadPdfView viewFromXib];
        _bottomView.frame = CGRectMake(0, self.view.frame.size.height-50, self.view.frame.size.width, 50);
        kWeakObject(self)
        _bottomView.tapBlock = ^(NSInteger index) {
            switch (index) {
                case 0:{
                    //习题点击
                    GMExercisesVC *vc = [[GMExercisesVC alloc] init];
                    vc.resId = weakself.resId;
                    [weakself.navigationController pushViewController:vc animated:YES];
                }
                    break;
                case 1:{
                    //附件点击
                    //发送通知，暂停播放
                    GMEnclosureVC *vc = [[GMEnclosureVC alloc] init];
                    vc.encolseureBlock = ^(GMAttachListModel *model) {
                        GMLookPDFVC *preVc = [[GMLookPDFVC alloc] init];
                        preVc.model = model;
                        [weakself.navigationController pushViewController:preVc animated:YES];
                    };
                    vc.dataArr = weakself.model.AttachList;
                    [weakself.navigationController presentSemiViewController:vc withOptions:@{
                                                                                          KNSemiModalOptionKeys.pushParentBack    : @(NO),
                                                                                          KNSemiModalOptionKeys.animationDuration : @(0.6),
                                                                                          KNSemiModalOptionKeys.shadowOpacity     : @(0.3)
                                                                                          }];
                }
                    break;
                case 2:{
                    //评论点击
                    GMCommentVC *conment = [[GMCommentVC alloc] init];
                    conment.resId = weakself.resId;
                    [weakself.navigationController pushViewController:conment animated:YES];
                }
                    break;
                case 3:{
                    //问题点击
                    GMQustionVC *conment = [[GMQustionVC alloc] init];
                    conment.resId = weakself.resId;
                    [weakself.navigationController pushViewController:conment animated:YES];
                }
                    break;
                case 4:{
                     //知识点击
                    GMKnowlegeVC *conment = [[GMKnowlegeVC alloc] init];
                    conment.dataArr = weakself.model.Dirs;
                    [weakself.navigationController pushViewController:conment animated:YES];
                }
                    break;
                case 5:{
                     //笔记点击
                    GMNoteVC *conment = [[GMNoteVC alloc] init];
                    conment.resId = weakself.resId;
                    [weakself.navigationController pushViewController:conment animated:YES];
                }
                    break;
                    
                default:
                    break;
            }
        };
    }
    return _bottomView;
}
/**文件分享*/
-(void)shareMyFile{
    XZShareController *shareVC = [[XZShareController alloc] init];
    shareVC.shareTitle = self.model.Name;
    shareVC.shareContent = self.model.FromName;
    shareVC.shareUrl =self.model.Url;
    shareVC.shareImgUrl = self.model.HeadUrl;
    shareVC.resId = self.resId;
    [self.navigationController presentSemiViewController:shareVC withOptions:@{
                                                                               KNSemiModalOptionKeys.pushParentBack    : @(NO),
                                                                               KNSemiModalOptionKeys.animationDuration : @(0.6),
                                                                               KNSemiModalOptionKeys.shadowOpacity     : @(0.3)
                                                                               }];
}
-(void)updateReadWithPag:(NSInteger )pag{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:self.resId forKey:@"resId"];
    [dict setValue:@(pag) forKey:@"pageNo"];
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=PostPagingData&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
       
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
